package com.dpj.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.ScheduledTaskExecution")
/*
    the test question is:
        How to execute the task regularly every Thursday at 18:00:00
 */

public class ScheduledTaskExecution {
    public static void main(String[] args) {

        // get the current time
        LocalDateTime now = LocalDateTime.now();
        //get the Thursday time
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);

        // ru guo dang qian shi jian > ben zhou zhou si ,bi xu zhao dao xia zhou zhou si
        if(now.compareTo(time)>0){
            time=time.plusWeeks(1);
        }
        long initailyDelay = Duration.between(now, time).toMillis();

        // initailyDelay:  dai biao dang qian shi jian he zhou si de shi jian cha
        //period : dai biao yi zhou de jian ge shi jian
        long period=1000*60*60*24*7;

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(()->{
            System.out.println("running");
        },initailyDelay,period, TimeUnit.MILLISECONDS);
    }
}
